package com.zmj.sy.mom.srv.aps.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import com.zmj.sy.mom.srv.aps.bean.dto.wms.MesPicking;
import com.zmj.sy.mom.srv.aps.bean.entity.base.BaseEntity;
import com.zmj.sy.mom.srv.aps.bean.entity.base.ProcessChain;
import com.zmj.sy.mom.srv.aps.bean.entity.base.ProcessChainItem;
import com.zmj.sy.mom.srv.aps.bean.entity.order.*;
import com.zmj.sy.mom.srv.aps.bean.entity.resource.PhaseGroup;
import com.zmj.sy.mom.srv.aps.bean.vo.base.Result;
import com.zmj.sy.mom.srv.aps.bean.vo.order.OrderExternalSyncErrorResVo;
import com.zmj.sy.mom.srv.aps.bean.vo.orderbom.OrderBomAppendReqVo;
import com.zmj.sy.mom.srv.aps.bean.vo.orderbom.OrderBomBatchAddReqVo;
import com.zmj.sy.mom.srv.aps.bean.vo.orderbom.OrderBomEditReqVo;
import com.zmj.sy.mom.srv.aps.feign.WmsLtkApiClient;
import com.zmj.sy.mom.srv.aps.mapper.*;
import com.zmj.sy.mom.srv.aps.utils.MkBeanUtils;
import com.zmj.sy.mom.srv.aps.utils.SyExceptionUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
@Slf4j
public class OrderBomService {

    private final OrderBomMapper orderBomMapper;
    private final OrderMapper orderMapper;
    private final ApsWorkOrderMapper apsWorkOrderMapper;
    private final OrderPhaseMapper orderPhaseMapper;
    private final ApsOrderMapper apsOrderMapper;
    private final ApsWorkDetailMapper apsWorkDetailMapper;
    private final SinoCamPushPlanMapper sinoCamPushPlanMapper;
    private final SinoCamPushDrawingMapper sinoCamPushDrawingMapper;
    private final OrderPartMapper orderPartMapper;
    private final ProcessChainItemMapper processChainItemMapper;
    private final ProcessChainMapper processChainMapper;
    private final ImportMbdDxfMapper importMbdDxfMapper;
    private final ImportErpBomMapper importErpBomMapper;
    private final ImportErpOrderMapper importErpOrderMapper;
    private final PhaseGroupMapper phaseGroupMapper;
    private final WmsService wmsService;
    private final WmsLtkApiClient wmsLtkApiClient;

    @Transactional
    public void edit(OrderBomEditReqVo reqVo) {

        OrderBom oldBom = orderBomMapper.selectById(reqVo.getId());
        OrderBom parent = orderBomMapper.selectById(oldBom.getPid());
        OrderBom orderBom = MkBeanUtils.copyProperties(reqVo, OrderBom.class);
        orderBom.setId(reqVo.getId());

        if (reqVo.getReadyType() == null) {
            throw SyExceptionUtils.e("没有备料方式");
        }

        Order order = orderMapper.selectById(oldBom.getOrderId());
        ProcessChain processChain = processChainMapper.selectById(reqVo.getProcessChainId());

        if (orderBom.getMaterType() == null) {
            throw SyExceptionUtils.e("没有物料类型");
        }
        if (orderBom.getMaterType().equals("Platepart") && order.getOrderType().equals(3)) {
            throw SyExceptionUtils.e("外揽订单没有自制件!");
        }

        if (orderBom.getMaterType().equals("Component") || processChain.getMyCode().equals("WL")) {
            orderBom.setWorkChain("WL");
            orderBom.setReadyType(2);
            orderBom.setMaterType("Component");
        } else {
            orderBom.setWorkChain("");
            orderBom.setReadyType(1);
        }

        orderBom.setErpCode(reqVo.getErpCode());// 添加
        orderBom.setMaterCode(orderBom.getPlmId());
        orderBom.setTopFlag(oldBom.getTopFlag());
        orderBom.setModifyStatus(LocalDateTime.now().format(DatePattern.PURE_DATETIME_FORMATTER));
        orderBom.setOrderId(oldBom.getOrderId());
        orderBom.setFactoryNo(oldBom.getFactoryNo());
        orderBom.setLevel(oldBom.getLevel());
        orderBom.setTotalCount(parent.getTotalCount().multiply(orderBom.getPartCount()));
        orderBom.setAssemblyPath(parent.getAssemblyPath() + "/" + orderBom.getMaterCode());
        orderBom.setMaterWeight(reqVo.getWeight());
        orderBom.setMaterHigh(reqVo.getMaterHigh());
        if (!StringUtils.hasText(orderBom.getDrawing())) {
            orderBom.setDrawing(orderBom.getPlmId().replace("_170", ""));
        }

        orderBom.setWorkChain(processChain.getMyCode());
        if (orderBom.getMaterType().equals("Platepart")) {
            if(!(StringUtils.hasText(orderBom.getTexture()) && orderBom.getMaterHigh() != null)){
                throw SyExceptionUtils.e("没有材质或厚度");
            }
            orderBom.setStandards(orderBom.getTexture() + "δ" + orderBom.getMaterHigh());
        }

        orderBomMapper.updateById(orderBom);

        // 工序相同则不动，工序不同走以下流程：
        // 如果以前是别的件改为外购件，则删除以前的工序
        // 如果以前是外购件，要改成自制件或者组件，则需要添加工序
        if(!orderBom.getWorkChain().equals(oldBom.getWorkChain())){
            // 删除以前的工序
            orderPhaseMapper.deleteByBomId(orderBom.getId());

            // 如果不是外购件，则新增工序
            if (!orderBom.getWorkChain().equals("WL")) {

                List<ProcessChainItem> itemList = processChainItemMapper.lambdaQuery().eq(ProcessChainItem::getChainId, reqVo.getProcessChainId()).orderByAsc(ProcessChainItem::getSeq).list();
                List<PhaseGroup> list = phaseGroupMapper.lambdaQuery().in(PhaseGroup::getPhaseCode, itemList.stream().map(ProcessChainItem::getMyCode).distinct().collect(Collectors.toList())).list();
                Map<String, List<PhaseGroup>> phaseGroupMap = list.stream().collect(Collectors.groupingBy(PhaseGroup::getPhaseCode));

                List<OrderPhase> orderPhaseList = itemList.stream()
                        .map(e -> {
                            OrderPhase item = new OrderPhase();
                            item.setBomId(orderBom.getId());
                            item.setOrderId(orderBom.getOrderId());
                            item.setWorkChain(orderBom.getWorkChain());
                            item.setPhaseName(e.getName());
                            item.setPhaseCode(e.getMyCode());
                            item.setPhaseSeq(e.getSeq());
                            item.setMaterNo(orderBom.getMaterCode());
                            item.setMaterName(orderBom.getMaterName());
                            if (item.getPhaseCode().equals("FM")) {
                                item.setWorkGroupNumber("4-3_FM_00");
                                item.setWorkTime(0);
                            } else if (item.getPhaseCode().equals("PT")) {
                                item.setWorkGroupNumber("4-3_PTX_00");
                                item.setWorkTime(10 * 60);
                            }

                            if(order.getOrderType().equals(4)){
                                item.setWorkTime(1);

                                List<PhaseGroup> phaseGroups = phaseGroupMap.get(e.getMyCode());
                                if(CollUtil.isNotEmpty(phaseGroups)){
                                    item.setWorkGroupNumber(phaseGroups.get(0).getGroupCode());
                                }
                            }
                            item.setOriWorkTime(item.getWorkTime());
                            return item;
                        })
                        .collect(Collectors.toList());
                orderPhaseMapper.insertBatchSomeColumn(orderPhaseList);
            }
        }



        if (order.getOrderStatus() <= 3 && reqVo.getReadyType().equals(2)) {
            return;
        }

        // 将 orderBom 进行写入，如果该条数据的父节点原本为普通节点，则要跟随修改其父节点的类别数据
        OrderPart one = orderPartMapper.lambdaQuery().eq(OrderPart::getPlmId, orderBom.getPlmId()).one();
        if (one == null) {
            OrderPart orderPart = new OrderPart();
            String code = orderBom.getPlmId();
            if (code.endsWith("_170")) {
                code = code.substring(0, code.indexOf("_170"));
            }
            ImportMbdDxf importMbdDxf = importMbdDxfMapper.lambdaQuery().eq(ImportMbdDxf::getPlmid, code).orderByDesc(ImportMbdDxf::getDocVersion).last("limit 1").one();

            orderPart.setPlmId(orderBom.getPlmId());
            // orderPart.setPngUrl(); // 零件PNG图纸路径
            // orderPart.setDxfUrl(); // 零件DXF图纸路径
            orderPart.setDrawing(orderBom.getDrawing());
            if (!Objects.equals(orderBom.getMaterType(), "Platepart")) {
                orderPart.setTexture(orderBom.getTexture());
            } else {
                orderPart.setTexture(orderBom.getTexture());
                orderPart.setThickness(new BigDecimal(orderBom.getMaterHigh()));
            }

            orderPart.setType(2); // 普通件
            orderPart.setNetWeight(orderBom.getMaterWeight());
            orderPart.setWorkChain(orderBom.getWorkChain()); // 工序链
            orderPart.setSource(orderBom.getReadyType()); // 备料方式：1 自制  2 外购
            orderPart.setVersionCode(1L); // 版本号
            orderPart.setMaterType(orderBom.getMaterType()); // 物料类别
            orderPart.setDrawStatus(1); // 是否制图就绪，默认 未就绪
            orderPart.setVersionNum(importMbdDxf != null ? importMbdDxf.getDocVersion() : null); // 图纸版本号
            orderPart.setDrawUpdateTime(null); // 图纸更新时间
            // orderPart.setLength(); // 宽度
            // orderPart.setWidth(); // 长度
            // orderPart.setArea(); // 面积
            // orderPart.setCritical(); // 是否关键件 0不是 1是
            orderPartMapper.insert(orderPart);
            one = orderPart;
        }

        if(order.getOrderStatus() <= 3){
            return ;
        }

        if (order.getOrderStatus() < 6) {
            order.setOrderStatus(3);
            orderMapper.updateById(order);
            return ;
        }

        List<ApsWorkOrder> oldWorkOrderList = apsWorkOrderMapper.lambdaQuery().eq(ApsWorkOrder::getBomId, orderBom.getId()).list();
        List<ApsOrder> apsOrderList = apsOrderMapper.lambdaQuery().eq(ApsOrder::getOrderId, order.getId()).list();
        Map<Integer, ApsOrder> apsOrderMap = apsOrderList.stream().collect(Collectors.toMap(BaseEntity::getId, Function.identity()));

        for (ApsWorkOrder apsWorkOrder : oldWorkOrderList) {
            ApsOrder apsOrder = apsOrderMap.get(apsWorkOrder.getApsOrderId());

            apsWorkOrder.setWorkOrderCode(orderBom.getWorkOrderCode());
            apsWorkOrder.setMaterName(orderBom.getMaterName());
            apsWorkOrder.setMaterCode(orderBom.getMaterCode());
            apsWorkOrder.setPlmId(orderBom.getPlmId());
            apsWorkOrder.setPartCount(orderBom.getPartCount());
            apsWorkOrder.setMaterHigh(orderBom.getMaterHigh());
            apsWorkOrder.setTexture(orderBom.getTexture());
            apsWorkOrder.setStandards(orderBom.getStandards());
            apsWorkOrder.setReadyType(orderBom.getReadyType());
            apsWorkOrder.setMaterType(orderBom.getMaterType());
            apsWorkOrder.setMaterWeight(orderBom.getMaterWeight());
            apsWorkOrder.setDrawing(orderBom.getDrawing());
            apsWorkOrder.setWorkChain(orderBom.getWorkChain());
            apsWorkOrder.setAssemblyPath(orderBom.getAssemblyPath());
            apsWorkOrder.setTotalCount(orderBom.getTotalCount());
            apsWorkOrder.setOrderCount(orderBom.getTotalCount().multiply(new BigDecimal(apsOrder.getOrderQty())));
            apsWorkOrderMapper.updateById(apsWorkOrder);

        }

        if(!orderBom.getWorkChain().equals(oldBom.getWorkChain()) && orderBom.getWorkChain().equals("WL")){
            // 发送到立体库
            wmsService.partProcurement(order.getId(), 0);
        } else if (!orderBom.getWorkChain().equals(oldBom.getWorkChain()) && oldBom.getWorkChain().equals("WL")){
            // 删除立体库的记录，并且清除领单号和领料顺序号
            if (CollUtil.isNotEmpty(oldWorkOrderList)) {
                List<MesPicking> pickList = oldWorkOrderList.stream().map(e -> {
                    MesPicking p = new MesPicking();
                    p.setPickListNo(Long.valueOf(e.getPickCode()));
                    p.setPickListItemNo(e.getPickSeq());
                    return p;
                }).collect(Collectors.toList());
                try {
                    Result result = wmsLtkApiClient.deletePickIng(pickList);
                    log.info("立体库删除外购件领料单结果：", result);

                    if (result.getCode() == 0) {
                        apsWorkOrderMapper.lambdaUpdate()
                                .in(ApsWorkOrder::getId, oldWorkOrderList.stream().map(ApsWorkOrder::getId).collect(Collectors.toList()))
                                .set(ApsWorkOrder::getPickCode, null)
                                .set(ApsWorkOrder::getPickSeq, null)
                                .update();
                    }
                } catch (Exception e) {
                    log.error("立体库删除外购件领料单异常：", e);
                }
            }
        }





        /*

        OrderBom orderBom = orderBomMapper.selectById(reqVo.getId());

        if (orderBom == null) {
            throw SyExceptionUtils.e("订单BOM不存在");
        }

//        if(!orderBom.getMaterType().equals("Platepart")){
//            throw SyExceptionUtils.e("只有零件可以修改BOM");
//        }

        Order order = orderMapper.selectById(orderBom.getOrderId());

//        if (orderBom.getPid() == null && (order.getOrderType().equals(3) || order.getOrderType().equals(4))) {
//            throw SyExceptionUtils.e("订单类型为工装订单或者外揽的订单不允许修改BOM");
//        }

        if (reqVo.getPartCount() != null && !reqVo.getPartCount().equals(orderBom.getPartCount())) {
            orderBom.setPartCount(reqVo.getPartCount());

            if(orderBom.getPid() != null){
                OrderBom parent = orderBomMapper.selectById(orderBom.getPid());
                orderBom.setTotalCount(parent.getTotalCount().multiply(reqVo.getPartCount()));
            } else {
                orderBom.setTotalCount(reqVo.getPartCount());
            }

            List<OrderBom> children = orderBomMapper.lambdaQuery().eq(OrderBom::getPid, orderBom.getId()).list();
            Map<Integer, OrderBom> parent = new HashMap<>();
            parent.put(orderBom.getId(), orderBom);

            while(CollUtil.isNotEmpty(children)){
                List<OrderBom> temp = new ArrayList<>();
                for(OrderBom child : children){
                    OrderBom p = parent.get(child.getPid());
                    child.setPartCount(child.getPartCount().multiply(p.getPartCount()));
                    parent.put(child.getId(), child);
                    temp.add(child);
                }

                if(CollUtil.isNotEmpty(temp)){
                    children = orderBomMapper.lambdaQuery().in(OrderBom::getPid, temp.stream().map(BaseEntity::getId).collect(Collectors.toList())).list();
                }
            }

            for (OrderBom value : parent.values()) {
                orderBomMapper.updateById(value);
            }

        }

        if(reqVo.getMaterHigh() != null){
            orderBom.setMaterHigh(reqVo.getMaterHigh());
        }

        if(reqVo.getWeight() != null){
            orderBom.setMaterWeight(reqVo.getWeight());
        }

        if (StringUtils.hasText(reqVo.getTexture())) {
            orderBom.setTexture(reqVo.getTexture());
        }

        orderBomMapper.updateById(orderBom);

        OrderPart one = orderPartMapper.lambdaQuery().eq(OrderPart::getPlmId, orderBom.getPlmId()).one();
        if(one != null){
            if(orderBom.getMaterHigh() != null){
                one.setThickness(new BigDecimal(orderBom.getMaterHigh()));
            }
            one.setNetWeight(orderBom.getMaterWeight());
            one.setTexture(orderBom.getTexture());
            orderPartMapper.updateById(one);
        }


        // 判断有没有工序，如果没有则返回
        List<OrderPhase> phaseList = orderPhaseMapper.lambdaQuery()
                .eq(OrderPhase::getOrderId, order.getId())
                .eq(OrderPhase::getBomId, orderBom.getId())
                .list();

        if (orderBom.getReadyType() != 2) {
            ProcessChain pc = processChainMapper.lambdaQuery().eq(ProcessChain::getId, reqVo.getProcessChainId()).one();
            if (pc != null && !pc.getMyCode().equals(orderBom.getWorkChain())) {
                if(order.getOrderStatus() >= 3){
                    throw SyExceptionUtils.e("订单已排产，不能修改工序");
                }

                for (OrderPhase orderPhase : phaseList) {
                    orderPhaseMapper.deleteRealById(orderPhase.getId());
                }

                List<ProcessChainItem> itemList = processChainItemMapper.lambdaQuery().eq(ProcessChainItem::getChainId, reqVo.getProcessChainId()).orderByAsc(ProcessChainItem::getSeq).list();
                List<OrderPhase> collect = itemList.stream()
                        .map(e -> {
                            OrderPhase item = new OrderPhase();
                            item.setBomId(orderBom.getId());
                            item.setOrderId(orderBom.getOrderId());
                            item.setWorkChain(orderBom.getWorkChain());
                            item.setPhaseName(e.getName());
                            item.setPhaseCode(e.getMyCode());
                            item.setPhaseSeq(e.getSeq());
                            item.setMaterNo(orderBom.getMaterCode());
                            item.setMaterName(orderBom.getMaterName());
                            return item;
                        })
                        .collect(Collectors.toList());

                orderPhaseMapper.insertBatchSomeColumn(collect);

                orderBom.setWorkChain(pc.getMyCode());
                orderBomMapper.updateById(orderBom);
                phaseList = collect;
            }
        }







        // 没有工序则返回
        if(CollUtil.isEmpty(phaseList)){
            return ;
        }

        // 未排产时，不需要管理后续操作
        if(order.getOrderStatus() < 5){
            return ;
        }

        // 如果已排产，则修改WorkOrder和WorkOrderDetail的数量
        List<ApsWorkOrder> workOrderList = apsWorkOrderMapper.lambdaQuery()
                .eq(ApsWorkOrder::getOrderId, order.getId())
                .eq(ApsWorkOrder::getBomId, orderBom.getId())
                .list();

        if(CollUtil.isEmpty(workOrderList)){
            return ;
        }
        List<Integer> apsOrderIds = workOrderList.stream().map(ApsWorkOrder::getApsOrderId).distinct().collect(Collectors.toList());
        List<ApsOrder> apsOrderList = apsOrderMapper.selectBatchIds(apsOrderIds);
        Map<Integer, ApsOrder> apsOrderMap = apsOrderList.stream().collect(Collectors.toMap(ApsOrder::getId, Function.identity()));

        for (ApsWorkOrder apsWorkOrder : workOrderList) {
            apsWorkOrder.setTotalCount(apsWorkOrder.getTotalCount());
            ApsOrder apsOrder = apsOrderMap.get(apsWorkOrder.getApsOrderId());
            apsWorkOrder.setOrderCount(new BigDecimal(apsOrder.getOrderQty()).multiply(apsWorkOrder.getTotalCount()));
            apsWorkOrder.setStandards(orderBom.getStandards());
            apsWorkOrder.setMaterHigh(orderBom.getMaterHigh());
            apsWorkOrder.setMaterWeight(orderBom.getMaterWeight());
            apsWorkOrder.setTexture(orderBom.getTexture());
            apsWorkOrderMapper.updateById(apsWorkOrder);
        }
        List<Integer> apsWorkOrderIdList = workOrderList.stream().map(BaseEntity::getId).collect(Collectors.toList());
        List<ApsWorkDetail> workDetailList = apsWorkDetailMapper.lambdaQuery()
                .in(ApsWorkDetail::getApsWorkOrderId, apsWorkOrderIdList)
                .list();

        if (CollUtil.isEmpty(workDetailList)) {
            return;
        }

        Map<Integer, ApsWorkOrder> workOrderMap = workOrderList.stream().collect(Collectors.toMap(ApsWorkOrder::getId, Function.identity()));

        for (ApsWorkDetail apsWorkDetail : workDetailList) {
            ApsWorkOrder apsWorkOrder = workOrderMap.get(apsWorkDetail.getApsWorkOrderId());
            apsWorkDetail.setTotalCount(apsWorkOrder.getOrderCount());
            apsWorkDetailMapper.updateById(apsWorkDetail);
        }

        if(order.getOrderStatus() < 7){
            return ;
        }

        // 如果大于7的时候，修改套料计划
        List<SinoCamPushDrawing> drawingList = sinoCamPushDrawingMapper.lambdaQuery()
                .eq(SinoCamPushDrawing::getOrderId, order.getId())
                .eq(SinoCamPushDrawing::getPartId, orderBom.getPlmId())
                .list();

        for (SinoCamPushDrawing sinoCamPushDrawing : drawingList) {
            sinoCamPushDrawing.setStatus(2);
            String[] split = orderBom.getStandards().split("δ");

            sinoCamPushDrawing.setNorm(orderBom.getStandards());

            if (!StringUtils.hasText(orderBom.getTexture())) {
                sinoCamPushDrawing.setTexture(split[0].trim());
            } else {
                sinoCamPushDrawing.setTexture(orderBom.getTexture());
            }
            if (orderBom.getMaterHigh() == null) {
                sinoCamPushDrawing.setThickNess(new BigDecimal(split[1].trim()));
            } else {
                sinoCamPushDrawing.setThickNess(new BigDecimal(orderBom.getMaterHigh()));
            }
            sinoCamPushDrawingMapper.updateById(sinoCamPushDrawing);
        }

        List<SinoCamPushPlan> planList = sinoCamPushPlanMapper.lambdaQuery()
                .eq(SinoCamPushPlan::getOrderId, order.getId())
                .in(SinoCamPushPlan::getNestPlanId, workDetailList.stream().map(e -> e.getId().toString()).distinct().collect(Collectors.toList()))
                .list();
        if(CollUtil.isEmpty(planList)){
            return ;
        }

        Map<Integer, ApsWorkDetail> detailMap = workDetailList.stream().filter(e -> e.getPhaseCode().equals("JG") || e.getPhaseCode().equals("HG")).collect(Collectors.toMap(e -> e.getId(), Function.identity()));
        for (SinoCamPushPlan pushPlan : planList) {
            ApsWorkDetail apsWorkDetail = detailMap.get(Integer.parseInt(pushPlan.getNestPlanId()));
            pushPlan.setPlanAmount(apsWorkDetail.getTotalCount());
            pushPlan.setStatus(2);
            sinoCamPushPlanMapper.updateById(pushPlan);
        }

        */
    }

    @Transactional
    public void batchAdd(List<OrderBomBatchAddReqVo> reqVoList) {

        if (CollUtil.isEmpty(reqVoList)) {
            return;
        }

        for (OrderBomBatchAddReqVo reqVo : reqVoList) {
            OrderBom orderBom = MkBeanUtils.copyProperties(reqVo, OrderBom.class);

            if(reqVo.getPid() == null){
                throw SyExceptionUtils.e("请选择父节点");
            }
            OrderBom parent = orderBomMapper.selectById(reqVo.getPid());

            Order order = orderMapper.selectById(parent.getOrderId());

            if(!parent.getMaterType().equals("Assembly")){
                throw SyExceptionUtils.e("父节点不是组件");
            }
            if(reqVo.getReadyType() == null){
                throw SyExceptionUtils.e("没有备料方式");
            }
            if (reqVo.getReadyType() == 2) {
                orderBom.setWorkChain("WL");
                parent.setMaterType("Component");
            } else {
                orderBom.setWorkChain("");
                parent.setMaterType("Platepart");

            }
            orderBom.setErpCode(reqVo.getErpCode());// 添加

            if (parent.getMaterType() == null) {
                throw SyExceptionUtils.e("没有物料类型");
            }

            orderBom.setMaterCode(orderBom.getPlmId());
            orderBom.setTopFlag(0);
            orderBom.setModifyStatus(LocalDateTime.now().format(DatePattern.PURE_DATETIME_FORMATTER));
            orderBom.setOrderId(parent.getOrderId());
            orderBom.setFactoryNo(parent.getFactoryNo());
            orderBom.setLevel(parent.getLevel() + 1);
            orderBom.setTotalCount(parent.getTotalCount().multiply(orderBom.getPartCount()));
            orderBom.setAssemblyPath(parent.getAssemblyPath() + "/" + orderBom.getMaterCode());
            orderBom.setMaterWeight(reqVo.getWeight());
            orderBom.setMaterHigh(reqVo.getMaterHigh());

            if (reqVo.getReadyType() != 2) {
                ProcessChain processChain = processChainMapper.selectById(reqVo.getProcessChainId());
                orderBom.setWorkChain(processChain.getMyCode());
            }

            orderBomMapper.insert(orderBom);

            if (reqVo.getReadyType() != 2) {
//                List<ProcessChainItem> itemList = processChainItemMapper.lambdaQuery().eq(ProcessChainItem::getChainId, reqVo.getProcessChainId()).orderByAsc(ProcessChainItem::getSeq).list();
                List<OrderPhase> collect = reqVo.getPhaseList().stream()
                        .map(e -> {
                            OrderPhase item = new OrderPhase();
                            item.setBomId(orderBom.getId());
                            item.setOrderId(orderBom.getOrderId());
                            item.setWorkChain(orderBom.getWorkChain());
                            item.setPhaseName(e.getPhaseName());
                            item.setPhaseCode(e.getPhaseCode());
                            item.setPhaseSeq(e.getPhaseSeq());
                            item.setMaterNo(orderBom.getMaterCode());
                            item.setMaterName(orderBom.getMaterName());
                            if (item.getPhaseCode().equals("FM")) {
                                item.setWorkGroupNumber("4-3_FM_00");
                            } else if (item.getPhaseCode().equals("PT")) {
                                item.setWorkGroupNumber("4-3_PTX_00");
                            }
                            return item;
                        })
                        .collect(Collectors.toList());

                orderPhaseMapper.insertBatchSomeColumn(collect);
           /* if (reqVo.getReadyType() == 3) {
                outScheduleOrder(order, parent ,orderBom, collect);
            }*/
            }

            // 将 orderBom 进行写入，如果该条数据的父节点原本为普通节点，则要跟随修改其父节点的类别数据
            OrderPart one = orderPartMapper.lambdaQuery().eq(OrderPart::getPlmId, orderBom.getPlmId()).one();
            if(one != null){
                return ;
            }
            OrderPart orderPart = new OrderPart();
            String code = orderBom.getPlmId();
            if (code.endsWith("_170")) {
                code = code.substring(0, code.indexOf("_170"));
            }
            ImportMbdDxf importMbdDxf = importMbdDxfMapper.lambdaQuery().eq(ImportMbdDxf::getPlmid, code).orderByDesc(ImportMbdDxf::getDocVersion).last("limit 1").one();

            orderPart.setPlmId(orderBom.getPlmId());
            // orderPart.setPngUrl(); // 零件PNG图纸路径
            // orderPart.setDxfUrl(); // 零件DXF图纸路径
            orderPart.setDrawing(orderBom.getDrawing());
            if (!Objects.equals(orderBom.getMaterType(), "Platepart")) {
                orderPart.setTexture(orderBom.getTexture());
            } else {
                orderBom.setStandards(orderBom.getTexture() + "δ" + orderBom.getMaterHigh());
                orderPart.setTexture(orderBom.getTexture());
                orderPart.setThickness(new BigDecimal(orderBom.getMaterHigh()));
            }
            // orderPart.setLength(); // 宽度
            // orderPart.setWidth(); // 长度
            orderPart.setType(2); // 普通件
            orderPart.setNetWeight(orderBom.getMaterWeight());
            // orderPart.setArea(); // 面积
            orderPart.setWorkChain(orderBom.getWorkChain()); // 工序链
            orderPart.setSource(orderBom.getReadyType()); // 备料方式：1 自制  2 外购
            // orderPart.setCritical(); // 是否关键件 0不是 1是
            orderPart.setVersionCode(1L); // 版本号
            orderPart.setMaterType(orderBom.getMaterType()); // 物料类别
            orderPart.setDrawStatus(1); // 是否制图就绪，默认 未就绪
            orderPart.setVersionNum(importMbdDxf != null ? importMbdDxf.getDocVersion() : null); // 图纸版本号
            orderPart.setDrawUpdateTime(null); // 图纸更新时间
            orderPartMapper.insert(orderPart);
        }


    }

    @Transactional(readOnly = true)
    public void append(OrderBomAppendReqVo reqVo) {

        List<OrderExternalSyncErrorResVo> errorList = new ArrayList<>();

        ImportErpBom currentBom = importErpBomMapper.selectById(reqVo.getId());
        if (currentBom == null) {
            throw SyExceptionUtils.e("没有找到该节点，请刷新后重试");
        }

        if ("R".equals(currentBom.getStatusId())) {
            throw SyExceptionUtils.e("该节点状态异常");
        }

        ImportErpOrder importErpOrder = importErpOrderMapper.selectById(currentBom.getErpOrderId());


    }
}
